import 'package:flutter/material.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_round.dart';
import 'package:flutter_09_game/pages/game/game_detail/widgets/widget_round_ball.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 单双球排布组件
/// 根据历史数据按照单双类型进行排布
/// 排布规则：从左往右、从上往下、每列最多5个、同一列只能是同一类型（单或双）
/// 支持自动滚动到最右边（最新数据）
///
///
class WidgetOddEvenLayout extends StatelessWidget {
  // const WidgetOddEvenLayout({super.key});
  final List<ModelGameRoundHistory> historyData;

  /// 球的大小，true为大球，false为小球
  final bool isBig;

  /// 每列最大项目数
  final int maxItemsPerColumn;
  final ScrollController scrollController;

  const WidgetOddEvenLayout({
    super.key,
    required this.historyData,
    this.isBig = true,
    this.maxItemsPerColumn = 5,
    required this.scrollController,
  });
  @override
  Widget build(BuildContext context) {
    List<List<int>> columns = _processHistoryData();

    if (columns.isEmpty) {
      return const SizedBox.shrink();
    }

    return SingleChildScrollView(
      controller: scrollController,
      scrollDirection: Axis.horizontal,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: _buildColumns(columns),
      ),
    );
  }

  /// 处理历史数据，转换为按列排布的二维数组
  /// 返回格式：List<List<int>> 其中每个内层List代表一列，包含该列的所有结果值
  List<List<int>> _processHistoryData() {
    if (historyData.isEmpty) return [];

    // 反转历史数据，使最新的数据显示在最左边
    final reversedHistoryData = historyData.reversed.toList();

    List<List<int>> columns = [];
    List<int> currentColumn = [];
    bool? currentColumnType; // true为单数，false为双数，null为未初始化

    for (var historyItem in reversedHistoryData) {
      int result = historyItem.result ?? 0;
      bool isOdd = result % 2 == 1;

      // 如果当前列为空，或者类型相同且未满，则添加到当前列
      if (currentColumn.isEmpty ||
          (currentColumnType == isOdd &&
              currentColumn.length < maxItemsPerColumn)) {
        currentColumn.add(result);
        currentColumnType = isOdd;
      } else {
        // 否则开始新的一列
        if (currentColumn.isNotEmpty) {
          columns.add(List.from(currentColumn));
        }
        currentColumn = [result];
        currentColumnType = isOdd;
      }
    }

    // 添加最后一列
    if (currentColumn.isNotEmpty) {
      columns.add(currentColumn);
    }

    return columns;
  }

  /// 构建列布局
  List<Widget> _buildColumns(List<List<int>> columns) {
    List<Widget> columnWidgets = [];

    for (int i = 0; i < columns.length; i++) {
      List<int> column = columns[i];

      // 构建单列
      Widget columnWidget = Column(
        mainAxisSize: MainAxisSize.min,
        children: column.asMap().entries.map(
          (entry) {
            int idx = entry.key;
            int result = entry.value;
            bool isLastColumn = (columns.length - 1 == i);
            bool isLastItemInColumn = (idx == column.length - 1);

            return Padding(
              padding: EdgeInsets.only(bottom: 8.w),
              child: WidgetRoundBall(
                result: result,
                isBig: isBig,
                isBorder: isLastColumn && isLastItemInColumn,
              ),
            );
          },
        ).toList(),
      );

      columnWidgets.add(columnWidget);
      // 添加列间距（除了最后一列）
      if (i < columns.length - 1) {
        columnWidgets.add(SizedBox(width: 8.w));
      }
    }

    return columnWidgets;
  }
}

// class WidgetOddEvenLayout extends StatefulWidget {
//   /// 历史数据列表
//   final List<ModelGameRoundHistory> historyData;
//
//   /// 球的大小，true为大球，false为小球
//   final bool isBig;
//
//   /// 每列最大项目数
//   final int maxItemsPerColumn;
//
//   const WidgetOddEvenLayout({
//     super.key,
//     required this.historyData,
//     this.isBig = true,
//     this.maxItemsPerColumn = 5,
//   });
//
//   @override
//   State<WidgetOddEvenLayout> createState() => _WidgetOddEvenLayoutState();
// }
//
// class _WidgetOddEvenLayoutState extends State<WidgetOddEvenLayout> {
//   late ScrollController _scrollController;
//
//   @override
//   void initState() {
//     super.initState();
//     _scrollController = ScrollController();
//
//     // 初始化后滚动到最右边
//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       _scrollToEnd();
//     });
//   }
//
//   @override
//   void didUpdateWidget(WidgetOddEvenLayout oldWidget) {
//     super.didUpdateWidget(oldWidget);
//
//     // 当数据更新时，自动滚动到最右边
//     if (widget.historyData.length != oldWidget.historyData.length) {
//       WidgetsBinding.instance.addPostFrameCallback((_) {
//         _scrollToEnd();
//       });
//     }
//   }
//
//   @override
//   void dispose() {
//     _scrollController.dispose();
//     super.dispose();
//   }
//
//   /// 滚动到最右边
//   void _scrollToEnd() {
//     if (_scrollController.hasClients) {
//       _scrollController.animateTo(
//         _scrollController.position.maxScrollExtent,
//         duration: const Duration(milliseconds: 300),
//         curve: Curves.easeOut,
//       );
//     }
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     // 处理历史数据，转换为排布结构
//
// }
